package cn.userBean.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.Remote;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import cn.model.User;
import cn.userBean.UserManager;

@Stateless(name="UserManagerBean")
@Remote
@TransactionManagement
public class UserManagerBean implements UserManager {

	@PersistenceContext(unitName = "my_test")
	private EntityManager em;

	@Resource
	private SessionContext ctx;

	public UserManagerBean() {
	}
	
	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public int addUser(User user) {
		try {
			em.persist(user);
			
		} catch (Exception e) {
			e.printStackTrace();
			ctx.setRollbackOnly();
			return 0;
		}
		return 1;
	}
	

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public int deleteUser(User user) {
		try {
			em.remove(user);
		} catch (Exception e) {
			e.printStackTrace();
			ctx.setRollbackOnly();
			return 0;
		}
		return 1;
	}

	

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public int updateUser(User user) {
		try {
			em.merge(user);
		} catch (Exception e) {
			e.printStackTrace();
			ctx.setRollbackOnly();
			return 0;
		}
		return 1;
	}

	@SuppressWarnings("unchecked")
	@Override
	@TransactionAttribute(TransactionAttributeType.SUPPORTS)
	public List<User> queryUser(User user) {
		List<User> userList = new ArrayList<User>();
		Query query = null;
		StringBuffer sql = new StringBuffer();
		sql.append("select * from user where 1 = 1 ");
		if (user != null) {
			if (user.getSex() != null && user.getSex() != "")
				sql.append(" and sex = " + user.getSex());
			if (user.getUserName() != null && user.getUserName() != "")
				sql.append(" and username = " + user.getUserName());
			if (user.getPassword() != null && user.getPassword() != "")
				sql.append(" and password = " + user.getPassword());
			if (user.getBirthDay() != null)
				sql.append(" and birthday = " + user.getBirthDay());
		} else
			query = em.createQuery(sql.toString());

		userList = query.getResultList();
		return userList;
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.SUPPORTS)
	public User findUser(int id) {
		return em.find(User.class, id);
	}

}
